package com.clstu.datasource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 这是一个基于Druid连接池的连接和释放资源的工具类
 */
public class JdbcUtilsByDruid {
    private static DataSource ds;
    //在静态代码块完成ds的初始化
    static {
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("src\\druid.properties"));
            ds = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //得到连接的方法
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    //关闭资源(把connection放回连接池)
    public static void close(ResultSet resultSet, Statement statement,Connection connection){
        try {
            if(resultSet!= null) resultSet.close();
            if (statement!=null) statement.close();
            if(connection!=null) connection.close();
        } catch (SQLException e) {
            //将编译异常转换为运行异常跑出
            throw  new RuntimeException(e);
        }
    }
}
